package com.sservice.web.controller.admin;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.sservice.base.SameUrlData;
import com.sservice.base.StringUtils;
import com.sservice.base.Utils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.Code;
import com.sservice.common.Constants;
import com.sservice.model.entity.Commission;
import com.sservice.model.entity.Order;
import com.sservice.model.entity.UserWx;
import com.sservice.model.vo.CommissionVo;
import com.sservice.model.vo.OrderVo;
import com.sservice.service.service.*;
import com.sservice.urp.entity.User;
import com.sservice.urp.vo.UserVo;
import com.sservice.web.log.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/order")
public class OrderController {
    @Autowired
    IUserWxService userWxService;
    @Autowired
    ICommissionService iCommissionService;
    @Autowired
    private IOrderService depService;
    @Autowired
    private ExportService exportService;
    @Autowired
    private ISysLogService sysLogService;

    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> create(Order arg) {
        int service_res = depService.insertSelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 申请退款
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryApplyPay", method = RequestMethod.GET)
    public ListResult queryApplyPay(OrderVo arg) {
        arg.setApplyBack("1");
        List orders = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, orders);
        res.setPage(page);
        return res;
    }

    /**
     * 积分详情
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult get(Order arg) {
        return new BaseResult(true, depService.detail(arg.getId(), null));
    }

    /**
     * 积分商品兑换订单详情
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exchangeDetail", method = RequestMethod.GET)
    public BaseResult exchangeDetail(Order arg) {
        return new BaseResult(true, depService.exchangeDetail(arg.getId(), null));
    }

    /**
     * 服务详情
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/serviceDetail", method = RequestMethod.GET)
    public BaseResult serviceDetail(Order arg) {
        return new BaseResult(true, depService.serviceDetail(arg.getId(), null));
    }

    /**
     * 付款的订单详情，商品不包括商品规格的商品详情
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/order-detail-no-spec", method = RequestMethod.GET)
    public BaseResult orderDetail(Order arg) { //
        return new BaseResult(true, depService.orderDetail(arg.getId(), arg.getNo()));
    }

    /***
     *  核销
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verified/{id}", method = RequestMethod.GET)
    public BaseResult verified(Order arg, HttpServletRequest requset) {
        Order order = depService.selectByPrimaryKey(arg.getId());
        if ("1".equals(order.getVerified())) {
            return new BaseResult(false, "订单已核销!", 403);
        }
        Order order1 = new Order();
        order1.setId(arg.getId());
        order1.setVerified("1");
        order1.setVerifiedTime(new Date());// 核销时间
        int service_res = depService.updateByPrimaryKeySelective(order1);
        if (service_res > 0) {
            sysLogService.log("订单核销", requset, arg.getId(), Action.orderType);
            return new BaseResult(true, "订单核销成功!", 200);
        }
        return new BaseResult(true, "订单核销失败!", 403);

    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete() {
        return new BaseResult();
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Order arg, HttpServletRequest request) {
        arg.setCheckStatus(null);//禁止通过update审核
        arg.setActualPrice(null); //禁止通过update收款
        arg.setPayStatus(null); //禁止通过update收款
        int service_res = depService.updateByPrimaryKeySelective(arg);
//        if (arg.getBusinessId() != null && arg.getSalesName() != null) {
//
//
//        }
        if ("8".equals(arg.getStatus())) {  //执行完成//
            Order order = depService.selectByPrimaryKey(arg.getId());
            UserWx userWx = userWxService.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
            if (!StringUtils.isEmpty(userWx.getPartnerId())) { //佣金
                BigDecimal total = depService.payCommission(order);
                Commission commission = new Commission(); // //
                commission.setType1(CommissionVo.generateType1(CommissionVo.DATA_TYPE1_ORDER_PARTNER, CommissionVo.BUSINESS_PARTNERID_COMMISSION_TYPE1));
                commission.setNo(order.getNo()); //合伙
                commission.setCommission(total);
                commission.setSaleId(userWx.getPartnerId());
                commission.setStatus("1");
                iCommissionService.save(commission);
//                    iCommissionService.giveCommission(Integer.valueOf(userWx.getPartnerId()), total);
            }
        }
        sysLogService.log("销售订单更新", request, arg.getId(), Action.orderType);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/setPayed", method = RequestMethod.POST)
    public BaseResult setPayed(Order arg) {
        arg.setPayStatus("1"); //禁止通过update收款
        if (arg.getActualTotal() == null || arg.getId() == null) {
            return new BaseResult(false, "", Code.INCOMPLETE_PARAMETERS);
        }
        Order order = depService.selectByPrimaryKey(arg.getId());
        order.setActualTotal(arg.getActualTotal());
        order.setPayStatus(arg.getPayStatus());
//        if(order.getTotal().compareTo(arg.getActualTotal())==-1){
//            return new BaseResult(false,"", Code.DATA_ERROR);
//        }
        depService.updateByPrimaryKeySelective(order);
        BaseResult<Integer> res = new BaseResult<Integer>(true, 1);
        return res;
    }


    /**
     * 收款
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/payed", method = RequestMethod.POST)
    public BaseResult<Object> payed(Order arg, HttpSession session, HttpServletRequest request) {
        Order order = new Order();
        BaseResult<Object> res = null;
        User user = (User) session.getAttribute(Constants.USER);
        order.setPayStatus("1");
        Order service_res = depService.selectByPrimaryKey(arg.getId());
        if (service_res != null) {
            if (!"0".equals(service_res.getStatus())) {
                return new BaseResult(false, "订单状态不在执行中，不能再次收款!", 403);
            }
            if (service_res.getPayStatus().equals("1")) {
                return new BaseResult(false, "订单已经收款，不能再次收款!", 403);
            }
            order.setActualTotal(service_res.getActualTotal());
            order.setId(arg.getId());
            order.setOfferId(String.valueOf(user.getId())); //操作员
            Integer pay_res = (Integer) depService.payed(order);
            if (pay_res > 0) {
                sysLogService.log("订单付款", request, order.getId(), Action.orderType);
                //orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_RECEIVE_MONEY, arg.getId().toString());
            }
            res = new BaseResult(true, pay_res);
        } else {
            res = new BaseResult(false, "订单不存在!", 403);
        }
        return res;
    }


    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/updatePrice", method = RequestMethod.POST)
    public BaseResult<Object> updatePrice(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = depService.selectByPrimaryKey(arg.getId());
        Object service_res = depService.updatePrice(arg);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("更新价格:" + order.getActualPrice() + "->" + arg.getActualPrice(), request, order.getId(), Action.orderType);
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }


    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/endOrder", method = RequestMethod.POST)
    public BaseResult<Object> endOrder(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = new Order();
        order.setId(arg.getId());
        order.setStatus("1");
        order.setReason(arg.getReason());
        Order order1 = depService.selectByPrimaryKey(arg.getId());
        Object service_res = depService.forceEnd(order);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("终止执行", request, order.getId(), Action.orderType);
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/checkStatus", method = RequestMethod.POST)
    public BaseResult<Object> checkStatus(Order arg, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(Constants.USER);

        arg.setChecker(String.valueOf(user.getId()));
        arg.setCheckTime(new Date());
        // 审核
        Object service_res = depService.checkOrder(arg); // 审核
        if (service_res instanceof String) {
            return new BaseResult<Object>(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                sysLogService.log("1".equals(arg.getCheckStatus()) ? "审核通过" : "审核拒绝", request, arg.getId(), Action.orderType);
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /***
     *  订单管理，分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(OrderVo arg, HttpSession session, boolean isExport) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);

        arg.setSalesName(String.valueOf(user.getId())); //
        if (isExport) return getExport(arg);
        List<OrderVo> list_order = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }


    /***
     *  服务申请管理，分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryApply", method = RequestMethod.GET)
    public ListResult queryApply(OrderVo arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        arg.setSalesName(String.valueOf(user.getId())); //
        List<OrderVo> list_order = depService.queryPlainByPage(arg);
        int total = depService.countPlainByPage(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    public ListResult getExport(OrderVo arg) {
        arg.setPage(0);
        arg.setSize(Integer.MAX_VALUE);
        List<OrderVo> list_order = depService.queryByPage(arg);
        return new ListResult(true, list_order);
    }

    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/cancel/{id}", method = RequestMethod.POST)
    public BaseResult<Integer> cancel(Order arg) throws WxPayException {
        Object object = depService.cancelOrder(arg.getId().toString());
        if (object instanceof String) {
            return new BaseResult(false, object.toString(), 403);
        }
        return new BaseResult(true, object.toString());
    }

    /**
     * 导出 订单功能
     *
     * @param arg
     * @param session
     * @return
     */
    @SameUrlData
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public OutputStream export(OrderVo arg, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {
        ListResult lr = query(arg, session, true);
        List<OrderVo> list = (List<OrderVo>) lr.getList();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/binary;charset=" + "UTF-8");
        String fileName = Utils.processFileName(request, "订单Excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");// 组装附件名称和格式
        response.setCharacterEncoding("UTF-8");
        String hql = "订单"; // sheet 名称
        List<Map> lm = new ArrayList<Map>();
        for (int i = 0; i < list.size(); i++) {
            Map map = new LinkedHashMap();
            OrderVo ov = list.get(i);
            map.put("订单编号", ov.getNo());
            map.put("客户名称", ov.getClienteleName());
            map.put("付款/发货/审核状态",
                    (ov.getPayStatus().equals("0") ? "未付款" : (ov.getPayStatus().equals("1") ? "已付款" : "部分付款")) + "/" +
                            (ov.getDeliverStatus().equals("0") ? "未发货" : (ov.getDeliverStatus().equals("1") ? "已全部发货" : "部分发货")) + "/" +
                            (ov.getCheckStatus().equals("0") ? "未审核" : (ov.getCheckStatus().equals("1") ? "通过" : "未通过"))
            );
            map.put("审核说明", ov.getReason());
            map.put("货物名称", ov.getGoodsName());
            map.put("品质规格", ov.getQuality());
            map.put("单价", ov.getActualPrice());
            map.put("数量", ov.getNumber());
            map.put("实提数量", ov.getActualNumber());
            map.put("发货数量", ov.getDeliverNumber());
            map.put("供货地", ov.getDeliverPlace());
            map.put("总金额", ov.getActualTotal());
            map.put("实收金额", ov.getActualTotal());
            map.put("订单状态", "1".equals(ov.getStatus()) ? "终止执行" : ("0".equals(ov.getStatus()) ? "执行中" : ("2".equals(ov.getStatus()) ? "强制执行完毕" : ("3".equals(ov.getStatus()) ? "执行完毕" : ""))));
            map.put("操作员", ov.getSaleName());
            map.put("业务员", ov.getSalesName());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("下单时间", ov.getCreateAt() != null ? sdf1.format(ov.getCreateAt()) : null);
            lm.add(map);
        }
        return exportService.exportExcel(hql, lm, outputStream);
    }


    @ResponseBody
    @RequestMapping(value = "/queryWithOffer", method = RequestMethod.GET)
    public ListResult<Order> queryWithOffer(OrderVo arg) {
        List<OrderVo> list = depService.queryWithOfferByPage(arg);
        int total = depService.countWithOfferByPage(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Order> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }
}
